package hanler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"lang-manager/cache"
	"lang-manager/model"
	"lang-manager/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "不能为空",
		})
		return
	}
	redis_key := "redis_" + username
	js, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if js >= 3 {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "密码错误,三次禁止登录",
		})
		return
	}
	var user model.User
	model.DB.Where("username = ?", username).First(&user)
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "该用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if js == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 200,
				"msg":  "密码错误3次，禁止登录2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "密码错误，请重新输入",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
	})
	return

}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var users []model.User
	redis_key := "redis_list" + strconv.Itoa(page)
	cahceData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cahceData == "" {
		model.DB.Offset(offset).Limit(size).Find(&users)
		js, _ := json.Marshal(users)
		cache.Rdb.Set(cache.Ctx, redis_key, js, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cahceData), &users)
	}
	var total int64
	model.DB.Model(&model.User{}).Count(&total)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "OK",
		"data": gin.H{
			"users": users,
			"total": total,
		},
	})
	return

}
